//
//  MineViewController.m
//  momo
//
//  Created by HappyMilk 02 on 2017/5/2.
//  Copyright © 2017年 tomi. All rights reserved.
//

#import "MineViewController.h"
#import "EmotionalViewCell.h"
#import "ReplyViewCell.h"
#import "MJRefresh.h"
#import "UserModel.h"
#import "UIImageView+WebCache.h"
#import "evelModel.h"
#import "PublicTool.h"

@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@property (weak, nonatomic) IBOutlet UIView *view_main;
@property (strong, nonatomic) IBOutlet UIImageView *imgv_head;
@property (weak, nonatomic) IBOutlet UILabel *lab_username;
@property (weak, nonatomic) IBOutlet UITextField *tf_username;

@property (weak, nonatomic) IBOutlet UITextField *tv_contents;
@property (weak, nonatomic) IBOutlet UILabel *lab_user_em;

@property (weak, nonatomic) IBOutlet UIView *view_xian;
@property (weak, nonatomic) IBOutlet UITableView *tabelview;

@property (weak, nonatomic) IBOutlet UILabel *lab_emotional;
@property (weak, nonatomic) IBOutlet UILabel *lab_reply;

@property (nonatomic) BOOL is_reply_tab;

@property (nonatomic ,strong) NSMutableArray *sendMsgArr;
@property (nonatomic ,strong) NSMutableArray *replyArr;

@end

@implementation MineViewController

- (IBAction)dismissvc:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];_is_reply_tab = NO;
    [evelModel registerSubclass];
    _sendMsgArr = [NSMutableArray array];
    _replyArr = [NSMutableArray array];
    // Do any additional setup after loading the view.
    
    [self modifyView];
    
    [self addRefreshControl];
    
    [self getUserInfometion];
    
    [self getUserSendMessage];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:_imgv_head.frame];
    [btn addTarget:self action:@selector(changeUserHeadImg) forControlEvents:UIControlEventTouchUpInside];
    [self.view_main addSubview:btn];
}
- (void)changeUserHeadImg{
    
    UIAlertController *alertcontroller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];//Import from album
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //拍照
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        //controller.mediaTypes=@[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
        controller.delegate = self;
        [self presentViewController:controller animated:YES completion:nil];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"From the album" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        if (IPAD) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            controller.delegate = self;
            UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:controller];
            [popover presentPopoverFromRect:CGRectMake(0, 0, 600, 800) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }else{
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            controller.delegate = self;
            [self presentViewController:controller animated:YES completion:nil];
        }
    }];
    [alertcontroller addAction:action];
    [alertcontroller addAction:action1];
    [alertcontroller addAction:action2];
    [self presentViewController:alertcontroller animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        _imgv_head.image = image;
        NSData *data = UIImagePNGRepresentation(image);
        
        AVQuery *query = [UserModel query];
        [query whereKey:@"user_id" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]];
        [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
            if (objects.count>0) {
                UserModel *model = [objects firstObject];
                AVFile *file = [AVFile fileWithData:data];
                [model setObject:file forKey:@"user_img"];
                [model saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                    NSLog(@"error --- %@",error);
                }];
            }
        }];
    }];
}
- (void)getUserReply{
    
    AVQuery *query1 = [AVQuery queryWithClassName:@"Evel_list"];
    [query1 whereKey:@"user_id" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]];
//    AVQuery *query2 = [AVQuery queryWithClassName:@"Evel_list"];
//    [query2 whereKey:@"msg_user_id" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]];
//    AVQuery *query = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:query1,query2, nil]];
    [query1 findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
       
        if (objects.count>0) {
            _replyArr = [objects mutableCopy];
            _is_reply_tab = YES;
            [self.tabelview reloadData];
        }
        NSLog(@"error --- %@",error);
    }];
}
- (void)getUserInfometion{
    
    AVQuery *query = [AVQuery queryWithClassName:@"User_list"];
    [query whereKey:@"user_id" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]];
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        if (objects.count>0) {
            UserModel *model = [objects firstObject];
            [_imgv_head sd_setImageWithURL:[NSURL URLWithString:model.user_img.url]];
            _lab_username.text = model.user_name;
            _lab_user_em.text = model.user_emotion;
        }
    }];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if ([textField isEqual:_tf_username]) {
        _lab_username.hidden = YES;
        return;
    }
    _lab_user_em.hidden = YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    AVQuery *query = [UserModel query];
    [query whereKey:@"user_id" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]];
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        if (objects.count>0) {
            UserModel *model = [objects firstObject];
            if ([textField isEqual:_tf_username]) {
                [model setObject:textField.text forKey:@"user_name"];
                [model saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                    NSLog(@"error --- %@",error);
                    [textField resignFirstResponder];
                    _lab_username.text = textField.text;
                    textField.text = @"";
                    _lab_username.hidden = NO;
                }];
            }else{
                [model setObject:textField.text forKey:@"user_emotion"];
                [model saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                    NSLog(@"error --- %@",error);
                    [textField resignFirstResponder];
                    _lab_user_em.text = textField.text;
                    textField.text = @"";
                    _lab_user_em.hidden = NO;
                }];
            }
        }
    }];
    return YES;
}

- (void)getUserSendMessage{
    
    AVQuery *query = [AVQuery queryWithClassName:@"Msg_list"];
    [query whereKey:@"user_id" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]];
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        if (objects.count>0) {
            _sendMsgArr = [objects mutableCopy];
            _is_reply_tab = NO;
            [self.tabelview reloadData];
        }
    }];
}

- (IBAction)emotionTabview:(UIButton *)sender {
    _is_reply_tab = NO;
    [self.tabelview.mj_header beginRefreshing];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.view_xian.frame = (CGRect){_lab_emotional.frame.origin.x,_lab_emotional.frame.origin.y+_lab_emotional.frame.size.height+7,_lab_emotional.frame.size.width,3};
    }];
}
- (IBAction)replyTabelview:(UIButton *)sender {
    
    [self getUserReply];
    _is_reply_tab = YES;
    [self.tabelview.mj_header beginRefreshing];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.view_xian.frame = (CGRect){_lab_reply.frame.origin.x,_lab_reply.frame.origin.y+_lab_reply.frame.size.height+7,_lab_reply.frame.size.width,3};
    }];
}

- (void)addRefreshControl{
    
    self.tabelview.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        
        [self.tabelview reloadData];
        [self.tabelview.mj_header endRefreshing];
    }];
}

- (void)modifyView{
    
    self.view_main.layer.masksToBounds = YES;
    self.view_main.layer.cornerRadius = 15;
    
    self.imgv_head.layer.masksToBounds = YES;
    self.imgv_head.layer.cornerRadius = 35;
    
    self.view_xian.frame = (CGRect){_lab_emotional.frame.origin.x,_lab_emotional.frame.origin.y+_lab_emotional.frame.size.height+7,_lab_emotional.frame.size.width,3};
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_is_reply_tab) {
        return _replyArr.count;
    }else{
        return _sendMsgArr.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_is_reply_tab) {
        evelModel *model = _replyArr[indexPath.row];
        static NSString *cellid = @"ReplyViewCell";
        ReplyViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ReplyViewCell" owner:nil options:nil] lastObject];
        }
        cell.lab_name.text = [NSString stringWithFormat:@"%@:",model.ev_name];
        cell.lab_contents.text = model.ev_contents;
        return cell;
    }else{
        MessageModel *model = _sendMsgArr[indexPath.row];
        static NSString *cellid = @"EmotionalViewCell";
        EmotionalViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"EmotionalViewCell" owner:nil options:nil] lastObject];
        }
        cell.model = model;
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.tv_contents resignFirstResponder];
    _lab_user_em.hidden = NO;
    [self.tf_username resignFirstResponder];
    _lab_username.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
